<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="active - 0"
        finish-status="success"
        class="el-steps-add"
        :align-center="true"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        label-position="top"
        label-width="80px"
        :model="formLabelAlign"
        :rules="rules"
        ref="reference"
      >
        <el-tabs
          style="height: 100%; margin-top: 15px"
          tabPosition="left"
          v-model="active"
          :before-leave="beforeleave"
          @tab-click="tabclick"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input
                v-model="formLabelAlign.goods_name"
                name="1"
                type="text"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="formLabelAlign.goods_price"
                name="2"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="formLabelAlign.goods_weight"
                name="3"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="formLabelAlign.goods_number"
                name="4"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 商品分类参数级联选择框 -->
              <div class="block">
                <el-cascader
                  clearable
                  v-model="formLabelAlign.goods_cat"
                  :options="catlist"
                  :props="options"
                  @change="getcat"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <!-- 参数 复选框-->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manylist"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  :label="item1"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlylist"
              :key="item.attr_id"
            >
              <el-input type="text" v-model="item.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <!-- 上传图片 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              list-type="picture"
              :headers="headerobj"
              :on-success="ptsuccess"
              :on-preview="pcpreview"
              :on-remove="pcremove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor
              ref="myQuillEditor"
              v-model="formLabelAlign.goods_introduce"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-button type="primary" @click="add">
        确定
      </el-button>
      <!-- 图片预览对话框 -->
      <el-dialog title="图片预览" :visible.sync="pcdialogVisible" width="50%">
        <img :src="pcpath" style="width: 100%" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 深拷贝工具包
import _ from 'lodash'
export default {
  data() {
    return {
      // 步骤数
      active: "0",
      // 基本信息form
      formLabelAlign: {
        goods_name: "", //商品名称
        goods_price: 0, //商品价格
        goods_weight: 0, //商品重量
        goods_number: 0, //商品数量
        goods_cat: [], //级联选择框的值,商品分类ID
        attrs:[],//商品的参数（数组），包含 动态参数 和 静态属性
        pics: [], //上传的图片临时路径
        goods_introduce:''//文件描述
      },
       manylist: [], //复选框 ，动态参数列表
        onlylist: [], //静态属性列表列表
      // 图片预览对话框开关
      pcdialogVisible: false,
      // 图片预览真实地址
      pcpath: "",
      // 图片上传请求头设置
      headerobj: {
        Authorization: window.sessionStorage.getItem("token"),
        //设置请求头 拦截器 request 属性Authorization=token 解决跨域问题，
        // 此配置在每次发起请求时 都会提请调用设置请求头Authorization
      },
      catlist: [], //分类列表
      // 级联选择器数据规则
      options: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //  基本form表单校验规则
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getcatlist(); //获取分类列表
  },
  computed: {
    catID() {
      return this.formLabelAlign.goods_cat[2];
    },
  },
  methods: {
    //获取分类列表
    async getcatlist() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.catlist = res.data;
    },
    // 级联选择器的值改变回调函数
    getcat(val) {
      console.log(val);
      if (val.length < 3) {
        return (this.formLabelAlign.goods_cat = []);
      } else {
        this.formLabelAlign.goods_cat = val;
      }
    },
    // tag页签切换之前调用的函数, return false:阻止切换
    beforeleave() {
      if (this.formLabelAlign.goods_cat.length < 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    // 点击tag商品参数和属性页签回调函数
    async tabclick(vc) {
      // console.log(this.catID);
      // 点击tag商品参数页签回调函数
      if (vc.index === "1" && this.formLabelAlign.goods_cat.length >= 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.catID}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        res.data.forEach((item) => {
          if (item.attr_vals !== "") item.attr_vals = item.attr_vals.split(" ");
        });
        this.manylist = res.data;
        console.log(this.manylist);
      }
      // 点击tag商品属性页签回调函数
      if (vc.index === "2" && this.formLabelAlign.goods_cat.length >= 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.catID}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.onlylist = res.data;
        console.log(this.onlylist);
      }
    },
    // 图片上传成功回调函数
    ptsuccess(response) {
      console.log(response);
      if (response.meta.status !== 200)
        return this.$message.error(response.meta.msg);
      const pc = { pic: response.data.tmp_path };
      this.formLabelAlign.pics.push(pc);
      console.log(this.formLabelAlign.pics);
    },
    // 图片预览回调函数
    pcpreview(file) {
      this.pcpath = file.response.data.url;
      this.pcdialogVisible = !this.pcdialogVisible;
      console.log(file);
    },
    // 图片移除回调函数
    pcremove(file) {
      // 数组索引查找方法findIndex(item => item.pic===file.response.data.tmp_path)
      let i = this.formLabelAlign.pics.findIndex(
        (item) => item.pic === file.response.data.tmp_path
      );
      //  数组删除元素方法splice(file.response.data.tmp_path,1)
      this.formLabelAlign.pics.splice(file.response.data.tmp_path, 1);
      console.log(this.formLabelAlign.pics);
      // console.log(file);
    },
    // 商品添加
  add(){
      this.$refs.reference.validate(async (valid) => {
          if (valid) {
            
              this.manylist.forEach(item =>{
                const a={}
                a.attr_id=item.attr_id
                a.attr_value=item.attr_vals.join(' ')
                this.formLabelAlign.attrs.push(a)
              })
           this.onlylist.forEach(item =>{
            //  console.log('aa');
             const a={}
                    a.attr_id=item.attr_id
                    a.attr_value=item.attr_vals
             this.formLabelAlign.attrs.push(a)
           })
           // 深拷贝
           const form=_.cloneDeep(this.formLabelAlign)
           form.goods_cat= form.goods_cat.join(',')
          const {data:res}=await  this.$http.post('goods',form)
          console.log(res);
          if(res.meta.status!==201){
            this.$message.error(res.meta.msg)
          }else{
            this.$router.push('/Goods')
           this.$message({
          message: res.meta.msg,
          type: 'success'
        });
          }
          } else {
            return this.$message.error('请填写必要的表单项');
          }
        });
    }
  },
};
</script>

<style scoped>
.el-steps-add {
  margin-top: 15px;
}
</style>